import type { Request, Response, NextFunction } from "express";
import { handleError, handleSucceed } from "@/utils/stateHandle";
import { JWT } from "@/utils/JWT";
import { logger } from "@/utils/log";

export const validateToken = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { token } = req.headers;
  logger.debug(token);
  if (!token) {
    return handleError(res, "未登录", 202);
  }

  try {
    if (JWT.verify(token.toString())) {
      return next();
    } else {
      return handleError(res, "登录已过期", 202);
    }
  } catch (err) {
    return handleError(res, err, 202);
  }
};
